import React, { useState, useEffect } from "react";
import { reqProduct, reqCategory } from "../../api";
import { Card, Button, List, message } from "antd";
import { ArrowLeftOutlined } from "@ant-design/icons";
import { useNavigate, useParams } from "react-router-dom";
import "./detail.less";

const Detail = () => {
  const [product, setProduct] = useState({});
  const [categoryName, setCategoryName] = useState("");
  const navigate = useNavigate();
  const { id } = useParams();

  useEffect(() => {
    const fetchProduct = async () => {
      const res = await reqProduct(id);
      if (res.status === 0) {
        setProduct(res.data);
        const categoryId = res.data.categoryId;
        if (categoryId) {
          const categoryRes = await reqCategory(categoryId);
          if (categoryRes.status === 0) {
            setCategoryName(categoryRes.data.name);
          } else {
            message.error(categoryRes.msg);
          }
        }
      } else {
        message.error(res.msg);
      }
    };

    fetchProduct();
  }, [id]);

  const title = (
    <span>
      <Button type="link" onClick={() => navigate(-1)}>
        <ArrowLeftOutlined />
      </Button>
      <span>商品详情</span>
    </span>
  );

  return (
    <Card title={title}>
      <List>
        <List.Item>
          <p>
            <span>商品名称:</span>
            <span>{product.name}</span>
          </p>
        </List.Item>
        <List.Item>
          <p>
            <span>商品描述:</span>
            <span>{product.desc}</span>
          </p>
        </List.Item>
        <List.Item>
          <p>
            <span>商品价格:</span>
            <span>{product.price}</span>
          </p>
        </List.Item>
        <List.Item>
          <p>
            <span>所属分类:</span>
            <span>{categoryName}</span>
          </p>
        </List.Item>
        <List.Item>
          <p>
            <span>商品图片:</span>
            <span>
              {product.imgs &&
                product.imgs.map((src) => (
                  <img
                    className="detail-img"
                    src={`http://localhost:5000/upload/${src}`}
                    alt="img"
                    key={src}
                  />
                ))}
            </span>
          </p>
        </List.Item>
        <List.Item>
          <span>商品详情:</span>
          <div dangerouslySetInnerHTML={{ __html: product.detail }}></div>
        </List.Item>
      </List>
    </Card>
  );
};

export default Detail;
